package TankFrst;
//可以调用RMI
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class MissileDeadMsg implements Msg{

    int msgType=Msg.TANK_DEAD_MSG;//tank死亡的消息
    int id;//子弹的id
    int tankId;//tank的id
    TankClient tc;

    public MissileDeadMsg(TankClient tc) {
        this.tc = tc;
    }

    public MissileDeadMsg(int tankId,int id) {
        this.tankId=tankId;
        this.id = id;
    }

    @Override
    public void send(DatagramSocket ds, String IP, int udpPort) {
        //利用send方法来发送信息
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//转换为字节输出
        DataOutputStream dos = new DataOutputStream(baos);
        try {
            /*
            将数据打包
            id,tank的横坐标和纵坐标，方向，坦克的好坏
             */
            dos.writeInt(msgType);
            dos.writeInt(id);
            dos.writeInt(tankId);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] buf = baos.toByteArray();//转换为字节数组
        DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress(IP, udpPort));//将字节数组转换为Data包发送
        try {
            ds.send(dp);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void parse(DataInputStream dis) {
        try {
            int tankId=dis.readInt();
            int id = dis.readInt();
            //判断tank是否被子弹达到，打到了则就移除子弹
            for (int i = 0; i < tc.missiles.size(); i++) {
                Missile m=tc.missiles.get(i);
                if (m.id == id) {
                    m.live=false;
                    tc.explodes.add(new Explode(tc,m.x,m.y));
                    break;
                }

            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
